package com.yita.demo01_base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class Demo02_Insert {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 1.加载驱动程序
        Class.forName("com.mysql.cj.jdbc.Driver");

        String url = "jdbc:mysql://localhost:13306/fruitdb";
        String user = "root";
        String pwd = "root";
        //2.获取数据库连接
        Connection conn = DriverManager.getConnection(url,user,pwd);

        //设置为0默认自增
        String sql = "insert into t_fruit values(0,?,?,?,?)";

        //3.创建PreparedStatement对象
        PreparedStatement preparedStatement = conn.prepareStatement(sql);
        preparedStatement.setString(1,"苹果");
        preparedStatement.setInt(2,12);
        preparedStatement.setInt(3,100);
        preparedStatement.setString(4,"m1.test");

        //4.执行SQL语句,执行增删改,返回受影响的行数
        int i = preparedStatement.executeUpdate();
        System.out.println(i>0?"插入成功":"插入失败");
        conn.close();
    }
}
